package com.wontube.smr.bo.sites.youtube.impl;

import java.util.ArrayList;
import java.util.List;

import com.wontube.smr.bo.sites.youtube.IYouTubeService;
import com.wontube.smr.model.vo.youtube.YouTubeVideoFile;
import com.wontube.smr.model.vo.youtube.YouTubeVideoType;




/**
 * @author yuechao
 *
 */
public final class CombineYouTubeService implements IYouTubeService {
	private final List<IYouTubeService> listService = new ArrayList<IYouTubeService>();
	private final List<YouTubeVideoFile> formats = new ArrayList<YouTubeVideoFile>();
	
	private String pageUrl;
	private String videoTitle;
	private String cookie;
	private String errMsg;
	
	public CombineYouTubeService() {
		this.listService.add(new APIYouTubeService());
		this.listService.add(new HtmlYouTubeService());
	}
	
	/* (non-Javadoc)
	 * @see smr.bo.video.youtube.IYouTubeService#createEmpty()
	 */
	@Override
	public IYouTubeService createEmpty() {
		return new CombineYouTubeService();
	}

	/* (non-Javadoc)
	 * @see smr.bo.video.youtube.IYouTubeService#obtain(java.lang.String)
	 */
	@Override
	public boolean obtain(String videoUrl) {
		this.pageUrl = videoUrl;
		for (IYouTubeService service : this.listService) {
			if (service.obtain(videoUrl)) {
				this.errMsg = null;
				this.videoTitle = service.getVideoTitle();
				this.cookie = service.getCookie();
				this.formats.clear();
				for (YouTubeVideoFile format : service.getFormats()) {
					this.formats.add(format);
				}
				return true;
			} else {
				this.errMsg = service.getErrMsg();
			}
		}
		
		return false;
	}

	/* (non-Javadoc)
	 * @see smr.bo.video.youtube.IYouTubeService#getPageUrl()
	 */
	@Override
	public String getPageUrl() {
		return this.pageUrl;
	}

	/* (non-Javadoc)
	 * @see smr.bo.video.youtube.IYouTubeService#getVideoTitle()
	 */
	@Override
	public String getVideoTitle() {
		return this.videoTitle;
	}

	/* (non-Javadoc)
	 * @see smr.bo.video.youtube.IYouTubeService#getCookie()
	 */
	@Override
	public String getCookie() {
		return this.cookie;
	}

	/* (non-Javadoc)
	 * @see smr.bo.video.youtube.IYouTubeService#getFormats()
	 */
	@Override
	public YouTubeVideoFile[] getFormats() {
		return this.formats.toArray(new YouTubeVideoFile[0]);
	}

	/* (non-Javadoc)
	 * @see smr.bo.video.youtube.IYouTubeService#getAvailableAudioFormat()
	 */
	@Override
	public YouTubeVideoFile[] getAvailableAudioFormat() {
		List<YouTubeVideoFile> list = new ArrayList<YouTubeVideoFile>();
		for (YouTubeVideoFile v : this.formats) {
			if (v.getVideoFormat() == YouTubeVideoType.Flash) {
				list.add(v);
			}
		}

		return list.toArray(new YouTubeVideoFile[0]);
	}
	
	@Override
	public String getErrMsg() {
		return this.errMsg;
	}
}
